<template>
    <div class="containers" ref="containers">
        <div id="js-canvas" class="canvas" ref="canvas"></div>
        <div id="js-properties-panel"></div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'; // 引入 Vue 3 的 API
import BpmnModeler from 'bpmn-js/lib/Modeler'; // 引入 bpmn-js
import customTranslate from './customTranslate/customTranslate'; // 汉化
import xmlStr from './xml'; // 引入默认显示的xml字符串数据
import propertiesPanelModule from 'bpmn-js-properties-panel';
import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';
import { createProcessDefine } from '@/http/processDefine'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter() // 获取 router 实例
// 创建响应式变量
const containers = ref(null);
const canvas = ref(null);
const bpmnModeler = ref(null);

const customTranslateModule = {
    translate: ['value', customTranslate],
};

// 初始化方法
const initDiagram = () => {
    bpmnModeler.value = new BpmnModeler({
        container: canvas.value,
        propertiesPanel: {
            parent: '#js-properties-panel',
        },
        additionalModules: [
            customTranslateModule,
            propertiesProviderModule,
            propertiesPanelModule,
        ],
        moddleExtensions: {
            camunda: camundaModdleDescriptor,
        },
    });
    // 元素选择变化
    bpmnModeler.value.on('selection.changed', (event) => {
        // console.log('选中元素:', event.newSelection);
    });

    // 元素点击
    bpmnModeler.value.on('element.click', (event) => {
        // console.log('点击元素:', event.element);
    });
    createNewDiagram();
};

// 创建新图表
const createNewDiagram = () => {
    const mr_xml = xmlStr; // 默认值-xml
    openDiagram(mr_xml);
};

// 创建新图表
const initNewDiagram = (xmlStr) => {
    openDiagram(xmlStr);
};

// 导入 XML 流程图
const openDiagram = (xml) => {
    bpmnModeler.value.importXML(xml);
};

// 导出 BPMN
const exportBpmn = () => {
    bpmnModeler.value.saveXML({ format: true })
        .then(({ xml }) => {
            console.log(xml); // 输出 XML，检查是否正常
            const blob = new Blob([xml], { type: 'text/xml' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'diagram.bpmn'; // 设置下载文件的名称
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        })
        .catch((err) => {
            console.error('Error exporting diagram:', err);
        });
};

const saveProcessDefine = () => {

    // 获取画布根元素（即流程定义元素）
    const rootElement = bpmnModeler.value.get('canvas').getRootElement();

    // 获取流程名称
    const processName = rootElement.businessObject.name;

    bpmnModeler.value.saveXML({ format: true })
        .then(({ xml }) => {
            // console.log(xml); // 输出 XML，检查是否正常
            createProcessDefine(JSON.stringify({
                name: processName,
                xml
            })).then(rep => {
                router.push("/bpmn/processdefineManage")
            }).catch(err => {

            })
        })
        .catch((err) => {
            console.error('Error exporting diagram:', err);
        });
};

// 使用 onMounted 来替代 mounted
onMounted(() => {
    initDiagram();
});

defineExpose({
    exportBpmn, saveProcessDefine, initNewDiagram
})
</script>

<style lang="scss">
/* 左边工具栏以及编辑节点的样式 */
@import 'bpmn-js/dist/assets/diagram-js.css';
@import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
@import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
@import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';

/* 右侧详情 */
@import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';

.containers {
    position: absolute;
    background-color: #ffffff;
    width: 100%;
    height: 100%;
    display: flex;

    .canvas {
        width: 100%;
        height: 100%;
    }

    .bjs-powered-by {
        display: none;
    }
}
</style>
